package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Account;
import com.example.mapper.AccountMapper;
import com.example.service.AccountService;
import com.example.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {



    /**
     * 查询用户钱包余额
     */
    public Double checkWalltById(Integer userId,String password) {

        //1.参数校验
        if(userId==null || StringUtils.isEmpty(password)){
            throw new RuntimeException("请正确输入id和密码");//由springMVC统一处理
        }

        //2.根据用户名查询是否存在该用户
        LambdaQueryWrapper<Account> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Account::getId,userId);
        Account account = getOne(lqw);

        if(account == null){
            throw new RuntimeException("该id对应的用户不存在");
        }
        //3.校验密码（一般采用MD5加密，这里就简单校验）
        if(!account.getPassword().equals(password)){
            throw new RuntimeException("密码错误");
        }
        //4.密码校对成功，查询数据库表，返回前端
        return account.getQuota();
    }



    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private LogService logService;

    /**
     *    用户消费100元
     * @param id
     * @param monetary 消费金额
     * @param userInpayPassword 用户输入的支付密码
     * @return
     */
    public String expenditure(Integer id,Double monetary,String userInpayPassword) {


        try {
            //1.根据id查询账户
            LambdaQueryWrapper<Account> lwq = new LambdaQueryWrapper<>();
            lwq.eq(Account::getId, id);
            Account account = getOne(lwq);

            //2.验证支付密码
            if(!account.getPayPassword().equals(userInpayPassword)){
                 throw new RuntimeException("支付密码不正确，请重试");
            }
            //3.判断余额是否充足
            if(monetary > account.getQuota()){
                throw new RuntimeException("账户余额不足！");
            }

            //4.修改表字段
            accountMapper.updateQuota(id, monetary);
        } finally {
            logService.log(id, "消费",monetary);
        }
        return "成功消费100元";
    }

    /**
     *
     * @param id 账户id
     * @param monetary 退款金额
     * @return
     */
    public String refund(Integer id,Double monetary){
        accountMapper.refundMonetary(id, monetary);
        logService.log(id, "退款", monetary);
        return "成功退款20元";
    }
}
